# import asyncio
# import aioredis
import redis
import json

redisPool = None

class ProxyEmptyError(Exception):
  def __init__(self):
    Exception.__init__(self)
  def __str__(self):
    return repr('The proxy source is exhausted')

def getRedisCfg():
  with open("E:\\projs\\my\\rediscfg.json", 'r') as f:
    REDIS_CFG = json.load(f)
    f.close()
    return REDIS_CFG

class RedisClient(object):
  def __init__(self):
    REDIS_CFG = getRedisCfg()
    self.redisPool = redis.ConnectionPool.from_url("redis://{0}:{1}/3".format(REDIS_CFG['host'], REDIS_CFG['port']),
                                                 password=REDIS_CFG['passwd'], max_connections=10,
                                                 decode_responses=True)
    self._db = redis.Redis(connection_pool=self.redisPool)

  def getClientFromPool(self):
    return redis.Redis(connection_pool=self.redisPool)

  def put(self, proxy):
    self._db.rpush("proxies", proxy)  # 右侧加入最新的代理

  def getAll(self):
    return self._db.lrange("proxies", 0, -1)

  def get(self):
    if self.queue_len > 0:
      proxies = self._db.rpop("proxies")  # 让列表只保留指定区间内的元素
      return proxies
    return None

  def pop(self):
    """
    get proxy from right.
    """
    try:
      return self._db.rpop("proxies")  # 右侧取出最新的代理
    except:
      raise ProxyEmptyError

  @property
  def queue_len(self):
    """
    get length from queue.
    """
    return self._db.llen("proxies")

  def clearQueue(self):
    self._db.ltrim("proxies", 0, -1)

def main():
  ins = RedisClient()
  # for i in range(10):
  #   ins.put( '李磊' + str(i))
  # ins.clearQueue()
  # print(ins.queue_len)
  # print(ins.getAll())
  for i in range(10):
    print(ins.pop())
  print(ins.getAll())

if __name__ == '__main__':
    main()

